package com.hiquety.csv2sql.modal;

import com.hiquety.csv2sql.tool.CsvSqlTool;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.stage.FileChooser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * @author hetong
 * @version 1.0
 * @date 2020-05-04
 */
public class IndexUI {

    @FXML
    public CheckBox lineCheck;
    @FXML
    private Button selectBtn;
    @FXML
    private TextField pathField;
    @FXML
    private TextArea sqlArea;

    public void selectBtnClick(MouseEvent mouseEvent) {
        FileChooser fileChooser = new FileChooser();
        File file = fileChooser.showOpenDialog(IndexFxml.stage);
        if (file == null) {
            return;
        }
        Csv.file = file;
        Csv.filePath = file.getAbsolutePath();
        Csv.fileName = "tt_" + file.getName().replace(".csv", "");
        pathField.setText(Csv.filePath);
        generateSql(file);
    }

    private void generateSql(File file) {
        if (file == null) {
            return;
        }
        FileInputStream is = null;
        InputStreamReader re = null;
        BufferedReader br = null;
        try {
            is = new FileInputStream(file);
            re = new InputStreamReader(is, "utf-8");
            br = new BufferedReader(re);

            // 删除表SQL
            String drop = CsvSqlTool.dropTable(Csv.fileName);
            // 创建表SQL
            String create = CsvSqlTool.createTable(br, Csv.fileName);
            // 插入数据SQL
            String insert = null;
            if (Csv.lineCheck) {
                insert = CsvSqlTool.insertTableByLine(br, Csv.fileName);
            } else {
                insert = CsvSqlTool.insertTableBatch(br, Csv.fileName);
            }

            sqlArea.clear();
            sqlArea.appendText("\n");
            sqlArea.appendText(drop);
            sqlArea.appendText("\n");
            sqlArea.appendText("\n");
            sqlArea.appendText(create);
            sqlArea.appendText("\n");
            sqlArea.appendText("\n");
            sqlArea.appendText(insert);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (re != null) {
                    re.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public void lineCheckClick(MouseEvent mouseEvent) {
        Csv.lineCheck = !Csv.lineCheck;
        generateSql(Csv.file);
    }
}
